package com.laker.autotest.common.listener;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.laker.autotest.common.config.EasyConfig;
import com.laker.autotest.common.config.EasyConfigFactory;
import com.laker.autotest.common.utils.TestNGUtil;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.testng.IExecutionListener;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
public class SendEmailListener implements IExecutionListener {
    final JavaMailSender javaMailSender = SpringUtil.getBean(JavaMailSender.class);
    final EasyConfig config = EasyConfigFactory.getConfig();

    /**
     * 整个 TestNG 测试运行完成后最后一步触发,比 IReporter.generateReport() 还要晚！
     */
    @Override
    public void onExecutionFinish() {
        log.info("🏁 全局测试执行已完成");
        if (config.isSendEmail()) {
            try {
                sendHtmlMail();
                log.info("📧 邮件已发送。");
            } catch (Exception e) {
                log.error("邮件发送失败，请检查配置或网络", e);
            }
        } else {
            log.warn("🚫 邮件功能被禁用（配置：easy.sendEmail=false）");
        }
    }

    private void sendHtmlMail() {
        try {
            MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
            //true表示需要创建一个multipart message
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            mimeMessageHelper.setFrom(config.getSenderEmail());
            mimeMessageHelper.setTo(config.getSendTo());
            mimeMessageHelper.setSubject(LocalDateTimeUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss") + " 自动化测试报告");
            String s = FileUtil.readString(new File(TestNGUtil.getReportDir(), TestNGUtil.getReportFileName()), StandardCharsets.UTF_8);
            mimeMessageHelper.setText(s, true);
            javaMailSender.send(mimeMailMessage);
            log.info("Send html email success.");
        } catch (MessagingException e) {
            log.error("Send html email error!", e);
        }
    }

}